package com.interceptors;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.util.ConfigUtil;
import com.util.SessionInfo;

/**   
 * @ClassName:  LoginInterceptor   
 * @Description: 
 * @author: 辛宇
 * @date:   2018年4月18日 下午4:58:00   
 */
@Repository
public class LoginInterceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3){

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("拦截器");
		String basePath = request.getServletPath();
		long timeup = 0;
		if( request.getSession().getAttribute("time")!=null){
			timeup = Long.parseLong(request.getSession().getAttribute("time").toString());
			long  thistime = System.currentTimeMillis();
			if(thistime-timeup> 5*60*1000){
				request.getSession().setAttribute(ConfigUtil.getSessionInfoName(), null);
			}
		}
		if(!basePath.endsWith("dbgzcontroller/test") ){
			request.getSession().setAttribute("time", System.currentTimeMillis());
		}		
		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(ConfigUtil.getSessionInfoName());
		if (sessionInfo == null){
			this.redirect(request, response);
			return false;
		}
		else 
			return true;
	}
	
	//对于请求是ajax请求重定向问题的处理方法
    public void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+request.getContextPath();
        //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            //告诉ajax我是重定向
            response.setHeader("REDIRECT", "REDIRECT");
            //告诉ajax我重定向的路径
            response.setHeader("CONTENTPATH", "/");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }else{
        	 PrintWriter writer = response.getWriter();  
        	 writer.write("/");  
            return;
        }
    }

}
